<script setup lang="ts">
import { getLatestVersion } from '@/api/system/version';
import { Version } from '@/api/system/version/type';
import { doCheckUpdate } from '@/utils/system';
import { path } from '@tauri-apps/api';
import { BaseDirectory, exists, mkdir } from '@tauri-apps/plugin-fs';
import { download, install } from '@tauri-apps/plugin-install';
import { type } from '@tauri-apps/plugin-os';
import { onMounted, ref } from 'vue';

const emit = defineEmits(["close"]);
const show = ref(false);
const version = ref({} as Version);
const percentage = ref(0);
const check = () => {
    doCheckUpdate().then((res) => {
        if (res) {
            getLatestVersion().then((res) => {
                version.value = res.data;
                show.value = true;
            })
        } else {
        }
    })
}
onMounted(() => {
    check();
})
const close = () => {
    show.value = false;
    emit("close");
}
const doUpdate = async () => {
    const osType = type();
    if (osType === 'android') {
        if (!await exists("files", { baseDir: BaseDirectory.AppData })) {
            await mkdir('files', {
                baseDir: BaseDirectory.AppData,
            });
        }
        const url = await path.appDataDir()+"/files/"+version.value.name+".apk";
        await download(version.value.url, url, ({progressTotal, total}) => {
            percentage.value = Math.floor(progressTotal * 100 / total);
        });
        await install(url);
    }
}
</script>

<template>
    <div>
        <van-dialog v-model:show="show" title="更新内容" 
            @cancel=""
            :show-confirm-button="true"
            :show-cancel-button="true"
        >
            <div class="content">
                <p>{{ version.content }}</p>
            </div>
            <template #footer>
                <div>
                    <div class="progress">
                        <van-progress :percentage="percentage" />
                    </div>
                    <div class="row">
                            <div class="half">
                                <van-button style="width: 100%;" @click="close">取消</van-button>
                            </div>
                            <div class="half">
                                <van-button style="width: 100%;" @click="doUpdate">确认</van-button>
                            </div>
                        </div>
                </div>
            </template>
        </van-dialog>
    </div>
</template>

<style lang="scss" scoped>
.progress {
    height: 30px;
    padding-left: 3%;
    padding-right: 3%;
}
.row {
    display: flex;
    width: 100%;
    justify-content: space-between;
    .half {
        width: 50%;
        align-items: center;
    }
}
.content {
    display: flex;
    justify-content: center;
    margin: 3%;
    height: 200px;
}
</style>